package edu.ynu.se.xiecheng.achitectureclass.service;
import edu.ynu.se.xiecheng.achitectureclass.dao.*;
import edu.ynu.se.xiecheng.achitectureclass.entity.*;
import edu.ynu.se.xiecheng.achitectureclass.service.SensorRequest;
import edu.ynu.se.xiecheng.achitectureclass.service.SensorDataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@Service
public class SensorService {

    private static final String API_URL = "https://fbox360.com/api/v2/dmon/value/get?boxNo=300822040454"; // boxNo 固定

    private final TokenService tokenService;
    private SoilWaterDataDao soilWaterDataDao;
    private SoilTemperatureDataDao soilTemperatureDataDao;
    private SoilNDataDao soilNDataDao;
    private AirTemperatureDataDao airTemperatureDataDao;
    private CO2DataDao cO2DataDao;
    private DeviceDao deviceDao;

    @Autowired
    public SensorService(TokenService tokenService,
                         SoilWaterDataDao soilWaterDataDao,
                         SoilTemperatureDataDao soilTemperatureDataDao,
                         SoilNDataDao soilNDataDao,
                         AirTemperatureDataDao airTemperatureDataDao,
                         CO2DataDao cO2DataDao,
                         DeviceDao deviceDao) {
        this.tokenService = tokenService;
        this.soilWaterDataDao = soilWaterDataDao;
        this.soilTemperatureDataDao = soilTemperatureDataDao;
        this.soilNDataDao = soilNDataDao;
        this.airTemperatureDataDao = airTemperatureDataDao;
        this.cO2DataDao = cO2DataDao;
        this.deviceDao = deviceDao;
    }

    // 获取传感器数据，不需要传参，直接使用固定值
    public List<SensorDataResponse> getSensorData() {
        String accessToken = tokenService.getAccessToken(); // 获取AccessToken

        // 创建请求体，直接使用固定的 IDs
        SensorRequest requestBody = new SensorRequest();
        requestBody.setIds(Arrays.asList(
                "327061586065758005",
                "327061586065758015",
                "327061586065758008",
                "327061586065758013",
                "327061586065758011"
        ));

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);

        // 设置请求体和请求头
        HttpEntity<SensorRequest> requestEntity = new HttpEntity<>(requestBody, headers);

        // 创建RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // 发送POST请求，URL不再需要boxNo路径变量
        ResponseEntity<SensorDataResponse[]> response = restTemplate.exchange(
                API_URL, HttpMethod.POST, requestEntity, SensorDataResponse[].class);

        // 如果请求成功，返回数据
        if (response.getStatusCode() == HttpStatus.OK) {
            saveSensorData(Arrays.asList(response.getBody()));
            return Arrays.asList(response.getBody());
        } else {
            throw new RuntimeException("获取传感器数据失败，状态码：" + response.getStatusCode());
        }
    }
    // 保存传感器数据到相应的实体
    private void saveSensorData(List<SensorDataResponse> sensorDataResponses) {
        for (SensorDataResponse data : sensorDataResponses) {
            switch (data.getId()) {
                case "327061586065758005": // 土壤含水率数据
                    saveSoilWaterData(data,Long.valueOf(1));
                    break;
                case "327061586065758015": // 土壤温度数据
                    saveSoilTemperatureData(data,Long.valueOf(2));
                    break;
                case "327061586065758008": // 土壤氮含量数据
                    saveSoilNitrogenData(data,Long.valueOf(3));
                    break;
                case "327061586065758013": // 空气温度数据
                    saveAirTemperatureData(data,Long.valueOf(4));
                    break;
                case "327061586065758011": // 二氧化碳数据
                    saveCo2Data(data,Long.valueOf(5));
                    break;
                default:
                    // 无匹配的ID，记录日志或处理异常
                    System.out.println("未知ID: " + data.getId());
            }
        }
    }

    // 将土壤水分数据保存到数据库
    private void saveSoilWaterData(SensorDataResponse data, Long deviceId) {
        SoilWaterDataEntity entity = new SoilWaterDataEntity();
        entity.setSensorNo(data.getId());
        entity.setDataValue(data.getValue());
        entity.setSensorName(data.getName());
        entity.setDataUnit("%");
        // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
        DeviceEntity device = deviceDao.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("Device not found"));

        // 设置外键关系，关联设备实体
        entity.setDevice(device);

        // 保存 SoilWaterDataEntity 实体
        soilWaterDataDao.save(entity);
    }

    // 将土壤温度数据保存到数据库
    private void saveSoilTemperatureData(SensorDataResponse data, Long deviceId) {
        SoilTemperatureDataEntity entity = new SoilTemperatureDataEntity();
        entity.setSensorNo(data.getId());
        entity.setDataValue(data.getValue());
        entity.setSensorName(data.getName());
        entity.setDataUnit("℃");

        // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
        DeviceEntity device = deviceDao.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("Device not found"));

        // 设置外键关系，关联设备实体
        entity.setDevice(device);

        soilTemperatureDataDao.save(entity);
    }

    // 将土壤氮含量数据保存到数据库
    private void saveSoilNitrogenData(SensorDataResponse data, Long deviceId) {
        SoilNDataEntity entity = new SoilNDataEntity();
        entity.setSensorNo(data.getId());
        entity.setDataValue(data.getValue());
        entity.setSensorName(data.getName());
        entity.setDataUnit("mg/kg");
        // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
        DeviceEntity device = deviceDao.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("Device not found"));

        // 设置外键关系，关联设备实体
        entity.setDevice(device);

        soilNDataDao.save(entity);
    }

    // 将空气温度数据保存到数据库
    private void saveAirTemperatureData(SensorDataResponse data, Long deviceId) {
        AirTemperatureDataEntity entity = new AirTemperatureDataEntity();
        entity.setSensorNo(data.getId());
        entity.setDataValue(data.getValue());
        entity.setSensorName(data.getName());
        entity.setDataUnit("℃");
        // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
        DeviceEntity device = deviceDao.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("Device not found"));

        // 设置外键关系，关联设备实体
        entity.setDevice(device);

        airTemperatureDataDao.save(entity);
    }

    // 将二氧化碳数据保存到数据库
    private void saveCo2Data(SensorDataResponse data, Long deviceId) {
        CO2DataEntity entity = new CO2DataEntity();
        entity.setSensorNo(data.getId());
        entity.setDataValue(data.getValue());
        entity.setSensorName(data.getName());
        entity.setDataUnit("ppm");
        // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
        DeviceEntity device = deviceDao.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("Device not found"));

        // 设置外键关系，关联设备实体
        entity.setDevice(device);

        cO2DataDao.save(entity);
    }
}